﻿using Devonline.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Devonline.Communication.Messages;

/// <summary>
/// 服务扩展方法
/// </summary>
public static class ServiceExtensions
{
    /// <summary>
    /// 注册通讯器
    /// </summary>
    /// <param name="builder">WebApplicationBuilder 实例</param>
    /// <param name="setup">在注册到依赖注入容器之前的处理方法</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static IServiceCollection AddCommunicator<TCommunicator>(this WebApplicationBuilder builder, Action<MessageOptions>? setup = null) where TCommunicator : class, IMessageCommunicator
    {
        var setting = builder.AddSetting<MessageOptions>(nameof(MessageOptions.Communicator));
        if (string.IsNullOrWhiteSpace(setting.Host) || string.IsNullOrWhiteSpace(setting.User))
        {
            throw new Exception("配置文件缺少必要的交互通讯配置");
        }

        setup?.Invoke(setting);
        return builder.Services.AddSingleton<IMessageCommunicator, TCommunicator>();
    }
    /// <summary>
    /// 使用默认的 MessageCommunicator 注入通讯器
    /// </summary>
    /// <param name="builder">WebApplicationBuilder 实例</param>
    /// <param name="setup">在注册到依赖注入容器之前的处理方法</param>
    /// <returns></returns>
    public static IServiceCollection AddCommunicator(this WebApplicationBuilder builder, Action<MessageOptions>? setup = null) => builder.AddCommunicator<MessageCommunicator>(setup);

    /// <summary>
    /// 注册通讯器
    /// </summary>
    /// <param name="services">依赖注入容器服务</param>
    /// <param name="options">Message Options 配置项的实例</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static IServiceCollection AddCommunicator<TCommunicator>(this IServiceCollection services, MessageOptions options) where TCommunicator : class, IMessageCommunicator
    {
        if (string.IsNullOrWhiteSpace(options.Host) || string.IsNullOrWhiteSpace(options.User))
        {
            throw new Exception("缺少必要的交互通讯配置");
        }

        return services.AddSetting(options).AddSingleton<IMessageCommunicator, TCommunicator>();
    }
    /// <summary>
    /// 注册默认通讯器
    /// </summary>
    /// <param name="services">依赖注入容器服务</param>
    /// <param name="options">Message Options 配置项的实例</param>
    /// <returns></returns>
    public static IServiceCollection AddCommunicator(this IServiceCollection services, MessageOptions options) => services.AddCommunicator<MessageCommunicator>(options);
}